﻿#ifndef _CLOCK_HPP_
#define _CLOCK_HPP_

#include<stdio.h>

#if defined(_WIN32)
#include <Windows.h>
#elif defined(__linux__)
#include <pthread.h>
#endif

#if defined(WIN32)
typedef CRITICAL_SECTION MutexType;
#elif defined(__linux__)
typedef pthread_mutex_t MutexType;
#endif

class CLock
{
public:
	CLock()
	{
#if defined(WIN32)
		InitializeCriticalSection(&_mutex);
#elif defined(__linux__)
		int r = pthread_mutex_init(&_mutex,NULL);
		if(r<0)
		{
			perror("CLock Construct");
			throw r;
		}
#endif
	}

	~CLock()
	{
#if defined(WIN32)
		DeleteCriticalSection(&_mutex);
#elif defined(__linux__)
		int r = pthread_mutex_destroy(&_mutex);
		if(r<0)
		{
			perror("CLock ~Construct");
			throw r;
		}
#endif
	}

	void Lock()
	{
#if defined(WIN32)
		EnterCriticalSection(&_mutex);
#elif defined(__linux__)
		int r = pthread_mutex_lock(&_mutex);
		if(r<0)
		{
			perror("CLock Lock");
			throw r;
		}
#endif
	}

	void Unlock()
	{	
#if defined(WIN32)
		LeaveCriticalSection(&_mutex);
#elif defined(__linux__)
		int r = pthread_mutex_unlock(&_mutex);
		if(r<0)
		{
			perror("CLock Unlock");
			throw r;
		}
#endif
	}
private:
	MutexType _mutex;
};


class CAutoLock
{
public:
	explicit CAutoLock(CLock& lock)
	{
		_plcok = &lock;
		lock.Lock();
	}

	~CAutoLock()
	{
		_plcok->Unlock();
	}
private:
	CLock* _plcok;
};

#endif
